﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;
using DataTable = System.Data.DataTable;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using System.Collections;

namespace ElectronicJournal.Account.AuthorAccount
{

    public partial class MyAccount : System.Web.UI.Page
    {
        public static event ChangingStateDelegate ChangingStateDelegateEvent;

        public class ArticleData
        {
            public Guid ArticleId { get; set; }
            public string ArticleTitle { get; set; }
            //public string JournalTitle { get; set; }
            public string ArticleContent { get; set; }
            public string ArticleState { get; set; }
            public bool IsPaid { get; set; }
            public string NumberPayment { get; set; }
            public string Notes { get; set; }
        }

        DataTable ArticleTable = new DataTable();

        public string GetCurrentArticleState(Guid articleId)
        {
            var autGuid = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());
            var state = EJournalRepository.Instance.GetStateByArticleId(articleId);
            if (state.StatePublished == true)
            {
                //ChangingStateDelegateEvent(autGuid, "опубликовано", articleId);
                return "опубликовано";
                
             //   SendingDelegate(Guid.Parse(Membership.GetUser().ProviderUserKey.ToString()), "опубликовано");
            }
            if (state.StateReturned == true)
            {
                //ChangingStateDelegateEvent(autGuid, "требуется доработка", articleId);
                return "требуется доработка";
            }
            if (state.StateRejected == true)
            {
                //ChangingStateDelegateEvent(autGuid, "отклонено", articleId);
                return "отклонено";
            }
            if(state.StateLoaded == true)
            {
                //ChangingStateDelegateEvent(autGuid, "подготовка", articleId);
                return "подготовка";
            }
            return "не загружено";

        }

        protected void ToCabitenLinkClick(object sender, EventArgs e)
        {
            MembershipUser user = Membership.GetUser();
            if (user != null)
                if (Roles.IsUserInRole(user.UserName, "Reviewer"))
                {
                    Response.Redirect("/Account/ReviewerAccount/Default.aspx");
                }
                else if (Roles.IsUserInRole(user.UserName, "Author"))
                {
                    Response.Redirect("/Account/AuthorAccount/Default.aspx");
                }
                else if (Roles.IsUserInRole(user.UserName, "Administrator"))
                {
                    Response.Redirect("/Account/ReviewerAccount/Default.aspx");
                }
                else if (Roles.IsUserInRole(user.UserName, "Editor"))
                {
                    Response.Redirect("/Account/EditorAccount/Default.aspx");
                }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            if (User.IsInRole("Author"))
            {
                if (!IsPostBack)
                {
                    ArrayList values = new ArrayList();
                    var currentAuthorsArticles = //EJournalRepository.Instance.GetAllPublications();
                        EJournalRepository.Instance.GetAllPublicationsForAuthor(
                            Guid.Parse(Membership.GetUser().ProviderUserKey.ToString()));

                    var controlIndex = 0;

                    foreach (var article in currentAuthorsArticles)
                    {
                        var newArt = new ArticleData()
                                         {
                                             ArticleId = article.Id,
                                             ArticleTitle = article.TitleRussian,
                                             ArticleContent = article.FileArticle,
                                             ArticleState = GetCurrentArticleState(article.Id),
                                             IsPaid =
                                                 (EJournalRepository.Instance.GetStateByArticleId(article.Id).StatePaid ==
                                                  true),
                                             //JournalTitle = "Журнал",// +// ",
                                             //EJournalRepository.Instance.GetJournalByPub(article.Id).JournalNumber.ToString(),
                                             NumberPayment = article.PubicationReceiptNumber
                                         };
                        
                        //if (newArt.ArticleState.Equals("требуется доработка"))
                        //{
                        //    var hlb = MainRepeater.Controls[++controlIndex].FindControl("ReloadLink") as HyperLink;
                        //    var r = hlb;
                        //    hlb.Visible = false;
                        //}
                        values.Add(newArt);
                        MainRepeater.DataSource = values;
                        MainRepeater.DataBind();
                        controlIndex++;
                        if (article.State.Equals(4))
                        {
                            var reloadLink = MainRepeater.Controls[controlIndex].FindControl("ReloadLink") as HyperLink;
                            if (reloadLink != null)
                            {
                                reloadLink.Visible = true;
                                reloadLink.NavigateUrl = "ReloadPublication.aspx?pubId=" + article.Id;
                            }
                        }
                    }

                   

                    // шаблон публикации
                    PatternFile.HRef = @"~\Patterns\" + Path.GetFileName(EJournalRepository.Instance.GetAllPattern().First().FileName);
                    ticketId.HRef = @"~\Receipt\ticket.doc";
                }
            }
            else
            {
                Response.Redirect("/IncorrectRole.aspx");
                return;
            }
        }


        DataTable _patternDataSource = new DataTable();
        protected void PatternTableLoad()
        {
            
            var listPattern = EJournalRepository.Instance.GetAllPattern();
            if (listPattern.Count != 0)
            {

                PatternListView.DataSource = _patternDataSource;
                _patternDataSource.Columns.Add("title", typeof (string));
                _patternDataSource.Columns.Add("description", typeof (string));
                _patternDataSource.Columns.Add("fileName", typeof (string));

                foreach (var pattern in listPattern)
                {
                    _patternDataSource.Rows.Add(pattern.Title, pattern.Description, @"~\Account\files\patterns\" + Path.GetFileName(pattern.FileName));
                }
               
                PatternListView.DataBind();
            }
        }

        //protected void ArticleTable_Load(object sender, EventArgs e)
        //{
        //    if (!IsPostBack)
        //    {
        //        try
        //        {
        //            var currentAuthorsArticles = EJournalRepository.Instance.GetAllPublicationsForAuthor(Guid.Parse(Membership.GetUser().ProviderUserKey.ToString()));

        //            foreach (var article in currentAuthorsArticles)
        //            {
        //                var currentArticleReviews = EJournalRepository.Instance.GetAllAuthorsReviews(article.Id);
        //                var state = EJournalRepository.Instance.GetStateByArticleId(article.Id);
        //                var reviewLink = string.Empty;

        //                if (currentArticleReviews.Count() > 0)
        //                {
        //                    if (state.StateId.Equals(3) | state.StateId.Equals(4))
        //                        reviewLink = currentArticleReviews.Last().ReviewContentLink;
        //                }

        //                ArticleTable.Rows.Add(
        //                    article.TitleRussian,
        //                    "Название журнала",
        //                    state.StateLoaded,
        //                    state.StateSentToReviewer,
        //                    state.StateReviewed,
        //                    state.StateReturned,
        //                    state.StateReady,
        //                    state.StatePaid,
        //                    state.StatePublished,
        //                    reviewLink,
        //                    article.PubicationReceiptNumber,
        //                    article.Id
        //                    );
        //            }
        //            //GridViewArticle.DataBind();
        //        }
        //        catch (NullReferenceException nrEx)
        //        {

        //        }
        //    }
        //}

        protected void GridViewRowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "ProofPayment")
            {
                LinkButton lbts = e.CommandSource as LinkButton;
                var id = lbts.FindControl("ArticleGuidLabel") as Label;
                Response.Redirect("ProofPayment.aspx?id=" + id.Text);
                return;
            }
            
            Button bts = e.CommandSource as Button;
            if (e.CommandName.ToLower() != "upload")
            {
                return;
            }
            FileUpload fu = bts.FindControl("NewArticleFileUpload") as FileUpload; 
            if (fu.HasFile)
            {
                string fleUpload = Path.GetExtension(fu.FileName.ToString());
                fu.SaveAs(Server.MapPath("..") + "\\files\\publications\\" + fu.FileName.ToString()); 
                string uploadedFile = (Server.MapPath(".." + "\\files\\pubications\\" + fu.FileName.ToString()));
            }
        }
                    
        protected void GridViewArticleRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row != null)
            {

            }
        }

        protected void GridViewArticle_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;
            if (drv != null)
            {
                bool dataBound = (bool)drv.Row[5];
                if (!dataBound)
                {
                    (e.Row.Cells[10].FindControl("UploadBtn") as Button).Enabled = false;
                    (e.Row.Cells[10].FindControl("NewArticleFileUpload") as FileUpload).Enabled = false;
                    //.Style.Add("visibility", "collapse");
                }
                bool dataBoundReview = (bool) drv.Row[3];
                if(!dataBoundReview)
                {
                    e.Row.Cells[9].Enabled = false;
                }

                var control = e.Row.Cells[10].FindControl("ArticleGuidLabel") as Label;
                control.Text = drv[11].ToString();
            }

        }

        public void FormTicketInDocument()
        {

            OrganizationInformation information = EJournalRepository.Instance.GetOrganizationInformation();
            Author author =
                EJournalRepository.Instance.GetAuthorByUserId(Guid.Parse(Membership.GetUser().ProviderUserKey.ToString()));

            object fileName = Server.MapPath(@"../../") + @"Receipt\Izveshenie.dot";
            Word.Application WordApp = new Application();
            WordApp.Visible = false;
            Word.Document WordDocument = WordApp.Documents.Open(fileName);
            
            // Заполнение полей информацией о получателе 
            object oBookMark = "INN";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.INN;
            oBookMark = "INN1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.INN; ;

            oBookMark = "NameAddressee";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.NameAddressee;
            oBookMark = "NameAddressee1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.NameAddressee;

            oBookMark = "CodePP";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.CodePP;
            oBookMark = "CodePP1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.CodePP;

            oBookMark = "NameBank";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.NameBank;
            oBookMark = "NameBank1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.NameBank;

            oBookMark = "BIK";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.BIK;
            oBookMark = "BIK1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.BIK;

            oBookMark = "SettlementAccount";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.SettlementAccount;
            oBookMark = "SettlementAccount1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.SettlementAccount;

            oBookMark = "NamePayment";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.NamePayment;
            oBookMark = "NamePayment1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.NamePayment;

            oBookMark = "PersonalAccountNumber";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.PersonalAccountNumber;
            oBookMark = "PersonalAccountNumber1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = information.PersonalAccountNumber;

            //Заполнение полей информацией о плательщике
            oBookMark = "FIO";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = author.AuthorFirstName + " "+ author.AuthorSecondName + " "+
                                                                        author.AuthorThirdName;
            oBookMark = "FIO1";
            WordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = author.AuthorFirstName + " " + author.AuthorSecondName + " " +
                                                                        author.AuthorThirdName;

            WordDocument.SaveAs(Server.MapPath(@"../../") + @"Receipt\ticket.doc");
            WordDocument.Application.Quit();
        }

        protected void GridViewArticle_SelectedIndexChanged(object sender, EventArgs e)
        {
            //e.
            ////drv = (DataRowView)e.Row.DataItem;
            //if (drv != null)
            //{
            //    bool dataBound = (bool)drv.Row[5];
        }

    }
}